package com.ruoyi.modules.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.LzmxEnum;
import com.ruoyi.common.enums.ZdjcEnum;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.modules.bean.*;
import com.ruoyi.modules.mapper.*;
import com.ruoyi.modules.service.*;
import com.ruoyi.modules.vo.SelectUserVo;
import com.ruoyi.modules.vo.XdrwVo;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zzw
 * @description 针对表【t_rwb(任务表)】的数据库操作Service实现
 * @createDate 2024-03-29 15:33:14
 */
@Service
@Slf4j
public class TRwbServiceImpl extends ServiceImpl<TRwbMapper,TRwb>
        implements TRwbService {

    @Autowired
    private TRwbMapper tRwbMapper;
    @Autowired
    private TFkbMapper tFkbMapper;
    @Autowired
    private TFjbMapper tFjbMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private TUserService tUserService;
    @Autowired
    private TUserFkService tUserFkService;

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private RuoYiConfig ruoYiConfig;
    @Autowired
    private SysUserMapper sysUserMapper;

    private static final String LZ_BASE_URL = "http://36.97.236.176:30100";
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private TFkbService tFkbService;
    @Autowired
    private LzDepartmentMapper lzDepartmentMapper;
    @Autowired
    private LzUserMapper lzUserMapper;
    @Autowired
    private LzUserLabelMapper lzUserLabelMapper;
    @Autowired
    private LzUserPostMapper lzUserPostMapper;
    @Autowired
    private LzCompanyMapper lzCompanyMapper;
    @Autowired
    private TSpbMapper tSpbMapper;
    @Autowired
    private TOptionService tOptionService;
    @Autowired
    private TZjxdRwbMapper tZjxdRwbMapper;
    @Autowired
    private TOptionMapper tOptionMapper;
    @Autowired
    private TUserOptionMapper tUserOptionMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private TUserFkMapper tUserFkMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public AjaxResult addxdwj(XdrwVo xdrwVo) {
        SysUser user = new SysUser();
        user = getLoginUser();
        TRwb rwb = xdrwVo.getRwb();
        if (rwb.getLzDepartmentId() != null) {
            LzDepartment lzDepartment = lzDepartmentMapper.selectById(rwb.getLzDepartmentId());
            rwb.setXdbm(lzDepartment.getName());// 下达部门
        }
        String sid = IdUtils.simpleUUID();
        rwb.setSid(sid);
        rwb.setIsTran("0");
        rwb.setXdr(user.getNickName());// 下达人
        rwb.setXdrId(String.valueOf(user.getUserId()));// 下达人id
        rwb.setLxdh(user.getPhonenumber());// 联系电话
//        rwb.setXdbm(String.valueOf(user.getDeptId()));// 下达部门
        SysDept sysDept = sysDeptMapper.selectDeptById(user.getDeptId());
        rwb.setXdjg(String.valueOf(getJgByBm(sysDept)));//下达机构
        rwb.setXdrq(DateUtils.getTime());
        List<TUserFk> users = new ArrayList<>();
        String workid = "";
        if ("2".equals(xdrwVo.getLy())) {// 移动端
            workid = xdrwVo.getWorkid();
            rwb.setWorkid(xdrwVo.getWorkid());
            tRwbMapper.insert(rwb);// 添加任务表信息
            users = addRedisUserToTUserFk(xdrwVo.getWorkid(),sid,xdrwVo.getUserFks());
        }else {
            workid = xdrwVo.getWorkid();
            rwb.setWorkid(xdrwVo.getWorkid());
            tRwbMapper.insert(rwb);// 添加任务表信息
           users = addRedisUserToTUserFk(xdrwVo.getWorkid(),sid);
        }

        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                if (StringUtils.isNotEmpty(fileName)){
                    fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                }
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success().put("workid",workid).put("sid",sid);
    }

    private List<TUserFk> addRedisUserToTUserFk(String workid,String rwbId) {
        String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
        List<TUserFk> users = getRedisUser(key);
        users.stream().forEach(user->user.setRwbId(rwbId));
        users = deduplicateById(users);
        long l = System.nanoTime();
        try {
            saveUserByLimit(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        tUserFkMapper.insertBatch(users);
        long l1 = System.nanoTime();
        System.out.println("添加人员用时" + (l1 - l) / 1000000000 + "ms");

        redisTemplate.delete(key);//删除缓存
        return users;
    }
    private List<TUserFk> addRedisUserToTUserFk(String workid,String rwbId,List<TUserFk> users) {
        String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
        users.stream().forEach(user->user.setRwbId(rwbId));
        users = deduplicateById(users);
        long l = System.nanoTime();
        try {
            saveUserByLimit(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        tUserFkMapper.insertBatch(users);
        long l1 = System.nanoTime();
        System.out.println("添加人员用时" + (l1 - l) / 1000000000 + "ms");

        redisTemplate.delete(key);//删除缓存
        return users;
    }
    private List<TUserFk> getRedisUser(String key){
        ListOperations<Object, Object> operations = redisTemplate.opsForList();
        List<Object> range =  operations.range(key, 0, -1);
        Object range1 = range;
        return (List<TUserFk>) range1;
    }


    @Override
    @Transactional
    public AjaxResult addZjxdwj(XdrwVo xdrwVo) {
        SysUser user = new SysUser();
        Long deptId = getLoginDept();
        user = getLoginUser();
        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        String sid = IdUtils.simpleUUID();
        zjxdRwb.setSid(sid);
        zjxdRwb.setIsTran("0");
        zjxdRwb.setXdr(user.getNickName());// 下达人
        zjxdRwb.setXdrId(String.valueOf(user.getUserId()));// 下达人id
        zjxdRwb.setLxdh(user.getPhonenumber());// 联系电话
        zjxdRwb.setXdbm(String.valueOf(user.getDeptId()));// 下达部门
        SysDept sysDept = sysDeptMapper.selectDeptById(user.getDeptId());
        zjxdRwb.setXdjg(String.valueOf(getJgByBm(sysDept)));//下达机构
        zjxdRwb.setXdrq(DateUtils.getTime());
        if ("2".equals(xdrwVo.getLy())) {// 移动端
            String workid = UUID.randomUUID().toString().replace("-", "");
            zjxdRwb.setWorkid(workid);
//            xdrwVo.setWorkid(workid);
            Result sendUser = addSendUser(xdrwVo.getDeptIds(), xdrwVo.getTabIds(), workid);
        }else {
//            zjxdRwb.setWorkid(xdrwVo.getWorkid());
        }
        tZjxdRwbMapper.insert(zjxdRwb);
        // 添加反馈信息
        List<String> deptIds = xdrwVo.getDeptIds();
        List<SysDept> sysDepts = sysDeptMapper.selectAllByDeptIdIn(deptIds);
        List<TOption> options = sysDepts.stream().map(d -> new TOption(sid, d.getDeptId(), d.getDeptName(), "0", d.getDeptLevel(),deptId,"")).collect(Collectors.toList());
        tOptionService.saveBatch(options);
        System.out.println(options);
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            }
        }
        // 发送消息到企业微信
        return AjaxResult.success();
    }
    @Override
    public AjaxResult addAppZjxdwj(XdrwVo xdrwVo) {
        List<String> deptIds = xdrwVo.getDeptIds();
        SysUser user = getLoginUser();
        List<String> loginRole = getLoginRoleNames(user);
        SysDept userDept = sysDeptMapper.selectDeptById(user.getDeptId());
        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        String sid = IdUtils.simpleUUID();
        zjxdRwb.setSid(sid);
        zjxdRwb.setIsTran("0");
        zjxdRwb.setXdr(user.getNickName());// 下达人
        zjxdRwb.setXdrId(String.valueOf(user.getUserId()));// 下达人id
        zjxdRwb.setLxdh(user.getPhonenumber());// 联系电话
        zjxdRwb.setXdbm(String.valueOf(user.getDeptId()));// 下达部门
        SysDept sysDept = sysDeptMapper.selectDeptById(user.getDeptId());
        zjxdRwb.setXdjg(String.valueOf(getJgByBm(sysDept)));//下达机构
        zjxdRwb.setXdrq(DateUtils.getTime());
        tZjxdRwbMapper.insert(zjxdRwb);
        // 添加反馈信息
        List<SysDept> sysDepts = sysDeptMapper.selectAllByDeptIdIn(deptIds);
        List<TOption> options = new ArrayList<>();
        if (loginRole.contains(ZdjcEnum.SJY.getValue())) {// 如果当前人角色是收件员转给科室主任、分管领导、一把领导
            options = sysDepts.stream().map(d -> new TOption(sid, d.getDeptId(), d.getDeptName(), "0", d.getDeptLevel()+ZdjcEnum.LD.getValue(), userDept.getDeptId(), null,getTranRoleId(d.getDeptName()),d.getDeptId())).collect(Collectors.toList());
            tOptionService.saveBatch(options);
        } else {// 如果当前人角色不是收件员转给收件员
            options = sysDepts.stream().map(d -> new TOption(sid, d.getDeptId(), d.getDeptName(), "0", d.getDeptLevel()+ZdjcEnum.SJY.getValue(), userDept.getDeptId(), null,  getTranRoleId(ZdjcEnum.SJY.getValue()),d.getDeptId())).collect(Collectors.toList());
            tOptionService.saveBatch(options);
            List<Long> roleIds2 = new ArrayList<>();
            roleIds2.add(ZdjcEnum.SJY_ID.getLongValue());
            addUserOption(options, zjxdRwb.getSid(),roleIds2);
        }
        System.out.println(options);
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success();
    }

    private void addUserOption(List<TOption> options, String rwbId,List<Long> roleIds) {
        // 添加人员意见关联表
        for (TOption option : options) {
            List<SysUser> userIds = tZjxdRwbMapper.getUserByDeptAndRoleId(option.getDeptId(), roleIds);
            for (SysUser sysUser : userIds) {
                TUserOption tUserOption = new TUserOption(sysUser.getUserId(), option.getId(), rwbId);
                tUserOptionMapper.insert(tUserOption);
            }
        }
    }

    private Long getTranRoleId(String deptName) {
        List<String> roleNames = new ArrayList<>();
        roleNames.add(deptName);
        List<Long> roleIds = sysRoleMapper.getRoleIdByRoleNameIn(roleNames);
        if (roleIds.size() == 0) {
            throw new RuntimeException("没有查到收件员角色");
        }
        return roleIds.get(0);
    }

    private  List<String> getLoginRoleNames(SysUser user) {
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(user.getUserId());// 获取人员角色
        if (sysRoles.size() ==0) throw new RuntimeException("请设置角色");
       return sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
    }
    private  List<SysRole> getLoginRoles(SysUser user) {
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(user.getUserId());// 获取人员角色
        if (sysRoles.size() ==0) throw new RuntimeException("请设置角色");
       return sysRoles;
    }

    @Override
    public PageInfo<TRwb> getRwPage(Map<String, String> params) {
        List<TRwb> rwbs = new ArrayList<>();
        if (params.containsKey("myMatter")) {
            params.put("xdrId", String.valueOf(getLoginUser().getUserId()));
        }
        PageHelper.startPage(getPage(params), getLimit(params));
        rwbs = tRwbMapper.getRwPage(params);
        if ("WEB".equalsIgnoreCase(params.get("ly"))) {
            addFksl(rwbs);// 添加反馈状态
        }
        // 格式化下达日期
        for (TRwb rwb : rwbs) {
            String xdrq = rwb.getXdrq();
            if (xdrq != null) {
                if (xdrq.contains(" ")) {
                    rwb.setXdrq(xdrq.split(" ")[0]);
                }
            }
        }
        PageInfo<TRwb> pageInfo = new PageInfo<>(rwbs);
        return pageInfo;
    }

    public PageInfo<TZjxdRwb> getZjxdRwPage(Map<String, Object> params) {
        SysUser user = getLoginUser();
        List<TZjxdRwb> rwbs = new ArrayList<>();
        Long deptId = user.getDeptId();
        if (deptId == null) {
            throw new RuntimeException("部门为空");
        }
        params.put("deptId", String.valueOf(deptId));
        PageHelper.startPage(getPage1(params), getLimit1(params));
        params.put("userId", user.getUserId());
        rwbs = tZjxdRwbMapper.getZjxdRwPage(params);
        addFkslZjxd(rwbs);// 添加反馈状态
        // 格式化下达日期
        for (TZjxdRwb rwb : rwbs) {
            String xdrq = rwb.getXdrq();
            if (xdrq != null) {
                if (xdrq.contains(" ")) {
                    rwb.setXdrq(xdrq.split(" ")[0]);
                }
            }
        }
        PageInfo<TZjxdRwb> pageInfo = new PageInfo<>(rwbs);
        return pageInfo;
    }

    @Override
    public PageInfo<TZjxdRwb> getAppZjxdRwPage(Map<String, Object> params) {
        SysUser user = sysUserMapper.selectUserbyAccountId(String.valueOf(params.get("username")));
        List<Long> loginRole = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<TZjxdRwb> rwbs = new ArrayList<>();
        Long deptId = user.getDeptId();
        if (deptId == null) {
            throw new RuntimeException("部门为空");
        }
        params.put("deptId", String.valueOf(deptId));
        params.put("roleIds", loginRole);
        params.put("userId", user.getUserId());
        PageHelper.startPage(getPage1(params), getLimit1(params));
        rwbs = tZjxdRwbMapper.getZjxdRwPage(params);
        addFkslZjxd(rwbs);// 添加反馈状态
        // 格式化下达日期
        for (TZjxdRwb rwb : rwbs) {
            String xdrq = rwb.getXdrq();
            if (xdrq != null) {
                if (xdrq.contains(" ")) {
                    rwb.setXdrq(xdrq.split(" ")[0]);
                }
            }
        }
        PageInfo<TZjxdRwb> pageInfo = new PageInfo<>(rwbs);
        return pageInfo;
    }

    @Override
    public TRwb getRwbInfo(String sid) {
        TRwb tRwb = tRwbMapper.selectById(sid);
//        if (tRwb.getXdrId() != null) {// 获取下达人部门
//            sysUserMapper.selectUserById(Long.valueOf(tRwb.getXdrId()));
//            Map params = new HashMap<>();
//            params.put("accountId", getLoginUser().getAccountId());
//            List<LzDepartment> departmentList = lzDepartmentMapper.getUserDepartment(params);
////            tRwb.setXdbm(departmentList.stream().map(LzDepartment::getName).collect(Collectors.joining(",")));
//          tRwb.setXdbmList(departmentList.stream().map(LzDepartment::getName).collect(Collectors.toList()));
//        }
        List<TRwb> rwbs = new ArrayList<>();
        rwbs.add(tRwb);
        addFksl(rwbs); // 添加反馈状态
        List<TFjb> tFjbs = getFjbs(sid);
        tRwb.setFjbs(tFjbs);
        List<File> files = new ArrayList<>();
        for (TFjb tFjb : tFjbs) {
            if (StringUtils.isNotEmpty(tFjb.getWjwldz())) {
                files.add(new File(tFjb.getWjwldz()));
            }
        }
        tRwb.setFjFile(files);

        // 返回MultipartFile对象
        return tRwb;
    }

    private List<TFjb> getFjbs(String sid) {
        QueryWrapper<TFjb> fjbWrapper = new QueryWrapper<>();
        fjbWrapper.eq("rwb_id", sid);
        List<TFjb> tFjbs = tFjbMapper.selectList(fjbWrapper);
        return tFjbs;
    }

    public TZjxdRwb getAppUserListByZjxdId(String sid) {
        TZjxdRwb tRwb = tZjxdRwbMapper.selectById(sid);
        addZjxdUserFksl(tRwb); // 添加反馈状态
        List<TFjb> tFjbs = getFjbs(sid);
        tRwb.setFjbs(tFjbs);
        List<File> files = new ArrayList<>();
        for (TFjb tFjb : tFjbs) {
            files.add(new File(tFjb.getWjwldz()));
        }
        tRwb.setFjFile(files);

        // 返回MultipartFile对象
        return tRwb;
    }

    @Override
    @Transactional
    public void delRwByIds(XdrwVo xdrwVo) {
        // 删除任务表
        List<String> ids = xdrwVo.getIds();
        tRwbMapper.deleteBatchIds(ids);
        // 删除任务表关联附件表
        QueryWrapper<TFjb> fjbQueryWrapper = new QueryWrapper<>();
        fjbQueryWrapper.in("rwb_id", ids);
        List<TFjb> tFjbs = tFjbMapper.selectList(fjbQueryWrapper);
        if (tFjbs.size() > 0) {
            tFjbMapper.deleteBatchIds(tFjbs);
            for (TFjb tFjb : tFjbs) {
                FileUtils.deleteFile(tFjb.getWjwldz()); // 删除附件物理地址
            }
        }
        tUserFkMapper.deleteByRwbIdIn(ids);// 删除人员反馈表
        //删除反馈表关联附件表
        List<TFjb> fjbs = tFjbMapper.getAllByFkbIdIn(ids);// 获取反馈表关联附件
        if (fjbs.size() > 0) {
            tFjbMapper.deleteBatchIds(fjbs);// 删除
            for (TFjb tFjb : fjbs) {
                FileUtils.deleteFile(tFjb.getWjwldz()); // 删除附件物理地址
            }
        }
    }
    @Override
    @Transactional
    public void delZjxdRwByIds(XdrwVo xdrwVo) {
        // 删除任务表
        List<String> ids = xdrwVo.getIds();
        List<TZjxdRwb> tRwbs = tZjxdRwbMapper.selectBatchIds(ids);
        tZjxdRwbMapper.deleteBatchIds(ids);
        // 删除任务表关联附件表
        QueryWrapper<TFjb> fjbQueryWrapper = new QueryWrapper<>();
        fjbQueryWrapper.in("rwb_id", ids);
        List<TFjb> tFjbs = tFjbMapper.selectList(fjbQueryWrapper);
        if (tFjbs.size() > 0) {
            tFjbMapper.deleteBatchIds(tFjbs);
            for (TFjb tFjb : tFjbs) {
                FileUtils.deleteFile(tFjb.getWjwldz()); // 删除附件物理地址
            }
        }
        // 删除关联反馈表
        tFkbMapper.deleteByRwbIdIn(ids);
        //删除反馈表关联附件表
        List<TFjb> fjbs = tFjbMapper.getAllByFkbIdIn(ids);// 获取反馈表关联附件
        if (fjbs.size() > 0) {
            tFjbMapper.deleteBatchIds(fjbs);// 删除
            for (TFjb tFjb : fjbs) {
                FileUtils.deleteFile(tFjb.getWjwldz()); // 删除附件物理地址
            }
        }
        // 删除关联user表
        for (TZjxdRwb tRwb : tRwbs) {
            removeUSerByWorkid(tRwb.getWorkid());
        }
        // 删除意见表
        tOptionMapper.deleteByRwbIdIn(ids);
        // 删除人员意见关联表
        tUserOptionMapper.deleteByRwbIdIn(ids);
    }

    @Override
    public void export(Map<String, String> params, HttpServletResponse response) {
        List<TUserFk> users = tUserFkMapper.getUserByRwId(params);
        addParentDept(users);
        addFkfj(users);
        ExcelUtil<TUserFk> util = new ExcelUtil<TUserFk>(TUserFk.class);
        util.exportExcel(response, users, "企业数据");
    }

    private void addFkfj(List<TUserFk> users) {
        for (TUserFk user : users) {
            Map map = new HashMap<>();
            map.put("fkb_id", user.getSid());
            List<TFjb> list = tFjbMapper.selectByMap(map);
            List<String> fileNameList = list.stream().map(TFjb::getWjmc).collect(Collectors.toList());
            List<String> fileUrlList = list.stream().map(TFjb::getWjdz).collect(Collectors.toList());
            Map<String, List<String>> fkfj = new HashMap<>();
            fkfj.put("fileNameList", fileNameList);
            fkfj.put("fileUrlList", fileUrlList);
            user.setFkfj(fkfj);
        }
    }

    private void addParentDept(List<TUserFk> users) {
        for (TUserFk user : users) {
            Map params1 = new HashMap<>();
            params1.put("userId", user.getUserId());
            List<LzDepartment> syjtDept = lzDepartmentMapper.getParentDept1(params1);
            if (syjtDept.size() > 0){
                user.setParentDept(StringUtils.isNotEmpty(syjtDept.get(0).getFullName()) ? syjtDept.get(0).getFullName() : syjtDept.get(0).getName());
            }
        }
    }

    @Override
    @Transactional
    public void updateRwb(XdrwVo xdrwVo) {
        TRwb rwb = xdrwVo.getRwb();
        String sid = rwb.getSid();
        tRwbMapper.updateById(rwb);// 修改下达任务
        // 修改附件表信息 先删除再添加
        UpdateWrapper<TFjb> fjbUpdateWrapper = new UpdateWrapper<>();
        fjbUpdateWrapper.eq("rwb_id", sid);
        tFjbMapper.delete(fjbUpdateWrapper);
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            } else {
                TFjb fjb = new TFjb();
                fjb.setWjdz(json.getString("url"));
                fjb.setWjwldz(json.getString("filePath"));
                String fileName = json.getString("name");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            }
        }
    }

    @Override
    public AjaxResult getFkxxByUserId(Map<String, String> params) {
        List<Map<String,String>> fkxxs= tRwbMapper.getFkxxByUserId(params);
        return AjaxResult.success(fkxxs);
    }

    @Override
    public AjaxResult getHistoryFkxxByUserId(Map<String, String> params) {
        List<Map<String,String>> fkxxs= tRwbMapper.getHistoryFkxxByUserId(params);
        return AjaxResult.success(fkxxs);
    }

    @Override
    public AjaxResult getFkxxInfo(Map<String, String> params) {
        // 反馈状态为未读变为已读
        String fkId = params.get("fkId");
        QueryWrapper<TUserFk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", fkId);
        TUserFk tUserFk = tUserFkMapper.selectOne(queryWrapper);
        if (ZdjcEnum.WD.getValue().equals(tUserFk.getZt())){// 如果状态为未读变为已读
            tUserFk.setZt(ZdjcEnum.YD.getValue());
            tUserFkMapper.updateById(tUserFk);
        }
        if ("1".equals(params.get("ly"))){
            TRwb tRwb = tRwbMapper.getFkxxInfo(params);
            List<TFjb> tFjbs = getFjbs(tRwb.getSid());
            tRwb.setFjbs(tFjbs);
            return AjaxResult.success(tRwb);
        }else{
            TZjxdRwb tZjxdRwb = tRwbMapper.getZjxdFkxxInfo(params);
            List<TFjb> tFjbs = getFjbs(tZjxdRwb.getSid());
            tZjxdRwb.setFjbs(tFjbs);
            return AjaxResult.success(tZjxdRwb);
        }
    }

    @Override
    public AjaxResult submitFk(XdrwVo xdrwVo) {
        UpdateWrapper<TUserFk> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("zt", ZdjcEnum.YFK.getValue());
        updateWrapper.set("fknr", xdrwVo.getFknr());
        updateWrapper.eq("sid", xdrwVo.getSid());
        tUserFkMapper.update(null, updateWrapper);
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setFkbId(xdrwVo.getSid());// 关联反馈表id
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success();
    }
    public AjaxResult submitAppZjxdFk(XdrwVo xdrwVo) {
        UpdateWrapper<TOption> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("fkzt", ZdjcEnum.YFK.getValue());
        updateWrapper.set("fknr", xdrwVo.getFknr());
        updateWrapper.eq("id", xdrwVo.getSid());
        tOptionMapper.update(null, updateWrapper);
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setFkbId(xdrwVo.getSid());// 关联反馈表id
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getFkFj(Map<String, String> params) {
        QueryWrapper<TFjb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fkb_id", params.get("fkId"));
        TUserFk tUserFk = tUserFkMapper.selectById(params.get("fkId"));
        return AjaxResult.success(tFjbMapper.selectList(queryWrapper)).put("fknr",tUserFk.getFknr());
    }

    @Override
    public AjaxResult getZjxdFkFj(Map<String, String> params) {
        QueryWrapper<TFjb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fkb_id", params.get("fkId"));
        TOption tOption = tOptionMapper.selectById(params.get("fkId"));
        return AjaxResult.success(tFjbMapper.selectList(queryWrapper)).put("fknr",tOption.getFknr());
    }

//    @Override
//    public AjaxResult getTxlDeptByid(String id){
//        String s = HttpUtils.senGetBasicAuto(ruoYiConfig.getApi() + ruoYiConfig.getDepartmentList()+"?id="+id, ruoYiConfig.getUsername(), ruoYiConfig.getPassword());
//        log.info("获取部门结果为" + s);
//        JSONObject result = JSONObject.parseObject(s);
//        System.out.println(result);
//        List<JSONObject> depts= (List<JSONObject>) result.get("department");
//        List<TreeNode<String>> nodeList = depts.stream().map(m -> new TreeNode<String>(m.getString("id"), m.getString("parentid"), m.getString("name"), m.getInteger("order"))).collect(Collectors.toList());
//        List<Tree<String>> trees = TreeUtils.build(nodeList, id);
//        Collections.reverse(trees);
//        return AjaxResult.success(trees);
//    }

    @Override
    public AjaxResult getTxlTab() {
        String s = HttpUtils.senGetBasicAuto(ruoYiConfig.getApi() + ruoYiConfig.getTagList(), ruoYiConfig.getUsername(), ruoYiConfig.getPassword());
        log.info("获取标签结果为" + s);
        JSONObject result = JSONObject.parseObject(s);
        if ("0".equals(result.getString("errcode"))) {// 成功
            JSONArray taglist = result.getJSONArray("taglist");
            return AjaxResult.success(taglist);
        } else {
            return AjaxResult.error(result.getString("errmsg"));
        }
    }

    public String getOpenUserId(Map<String, Object> map) {
        String resUserId = "";
        String s = HttpUtils.senPostBasicAuto(ruoYiConfig.getApi() + "batch/userid_to_openuserid", ruoYiConfig.getUsername(), ruoYiConfig.getPassword(), map);
        log.info("获取标签结果为" + s);
        JSONObject result = JSONObject.parseObject(s);
        if ("0".equals(result.getString("errcode"))) {// 成功
            resUserId = result.getJSONArray("open_userid_list").getJSONObject(0).getString("open_userid");
        }
        return resUserId;
    }

//    @Override
//    @Transactional
//    public AjaxResult getSelectUser(SelectUserVo selectUserVo) {
//        List<String> deptIds = selectUserVo.getDeptIds();
//        List<String> tabIds = selectUserVo.getTabIds();
//        String workid = UUID.randomUUID().toString().replace("-", "");
//        workid = selectUserVo.getWorkid();
//        Result result = getSendUser(deptIds, tabIds,workid);
//        if (result.getCode() == 200) {
//            return AjaxResult.success(workid);
//        } else {
//            return AjaxResult.error(result.getMsg());
//        }
//
//    }
    // 去重
    private static List<TUserFk> deduplicateById(List<TUserFk> users) {
        Map<String, TUserFk> map = new HashMap<>();
        List<TUserFk> newUsers = new ArrayList<>();
        for (TUserFk user : users) {

            if (!map.containsKey(user.getUserId())) {
                map.put(user.getUserId(), user);
                newUsers.add(user);
            } else {
                System.out.println("重复数据  id="+user.getUserId()+"name="+user.getName());
            }
        }
        return newUsers;
    }
    private void removeUSerByWorkid(String workid) {
        Map<String, Object> delMap = new HashMap<>();
        delMap.put("workid", workid);
        tUserService.removeByMap(delMap);// 先删除
    }

    @Override
    public TableDataInfo getSelectUserPage(Map<String, String> params) {
        String flag = params.get("flag");
        if ("false".equals(flag)) {
            QueryWrapper<TUserFk> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("workid", params.get("workid"));
            Page<TUserFk> page = tUserFkService.page(new Page<>(getPage(params), getLimit(params)), queryWrapper);
            return getTableDataInfo(page.getRecords(),page.getTotal());
        }else {
            String workid = params.get("workid");
            String name = params.get("name");// 人员姓名
            String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
            ListOperations<Object, Object> operations = redisTemplate.opsForList();
            int pageNum = getPage(params);
            int pageSize = getLimit(params);
            int start = (pageNum - 1) * pageSize;
            int end = start + pageSize - 1;
            Long size = operations.size(key);
            if (StringUtils.isEmpty(name)){
                List<Object> range =  operations.range(key, start, end);
                TableDataInfo rspData = getTableDataInfo(range, size);
                return rspData;
            }else {// 根据人员姓名查询
                List<TUserFk> tUserFkList =  getRedisUser(key);
                tUserFkList = tUserFkList.stream().filter(user -> user.getName()!=null? user.getName().contains(name):false).collect(Collectors.toList());
                TableDataInfo rspData = getTableDataInfo(tUserFkList, size);
                return rspData;
            }

        }
    }

    private static <T> TableDataInfo getTableDataInfo(List<T> range, Long size) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(range);
        rspData.setTotal(size);
        return rspData;
    }


    @Override
    public Page<TUser> getSelectZjxdUserPage(Map<String, String> params) {
        SysUser user = getLoginUser();
        Long deptId = user.getDeptId();
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("workid", params.get("workid"));
        queryWrapper.eq("create_dept", deptId);
        return tUserService.page(new Page<>(getPage(params), getLimit(params)), queryWrapper);
    }

    @Override
    public PageInfo<TUserFk> getUserByRwId(Map<String, String> params) {
        PageHelper.startPage(getPage(params), getLimit(params));
        List<TUserFk> users = tUserFkMapper.getUserByRwId(params);
        try {
            setCaReadstatus(users,params.get("rwId"));
            addParentDept(users);
        } catch (Exception e) {
            log.error("调用辰安获取人员读取状态"+e.getMessage());
        }
        return new PageInfo<>(users);
    }

    @Override
    public PageInfo<TOption> getZjxdUserByRwId(Map<String, String> params) {
        PageHelper.startPage(getPage(params), getLimit(params));
        List<TOption> options = tUserMapper.getZjxdUserByRwId(params);
        return new PageInfo<>(options);
    }

    @Override
    @Transactional
    public AjaxResult tranMessageByUser(XdrwVo xdrwVo) {
        if (StringUtils.isNoneEmpty(xdrwVo.getFkId())){
            tUserFkMapper.updateZfyjBySid(xdrwVo.getZfyj(),xdrwVo.getFkId());
        }
        TRwb rwb = xdrwVo.getRwb();
        try {
            if (rwb == null) {
                return AjaxResult.error("rwb参数为空");
            }
            if (rwb.getWorkid() == null) {
                return AjaxResult.error("workid为空");
            }
            String workid = rwb.getWorkid();
            List<String> deptIds = xdrwVo.getDeptIds();
            Map<String, Object> params = new HashMap<>();
            params.put("deptIds", deptIds);
            params.put("postWay", 1);
//            List<JSONObject> userlist = lzUserMapper.getUserBydeptAndLabel(params);
            List<JSONObject> userlist = lzUserMapper.getUserBydeptAndLabel1(params);// 转发给当前部门，不转发子部门
            List<TUserFk> users = buildUserFk(userlist, workid);
            // 去重
            users = deduplicateById(users);
            if (users.size() > 0) {
                users.stream().forEach(u -> u.setRwbId(rwb.getSid()));
                tUserFkMapper.insertBatch(users);
                messageSendByLimit(users, rwb, 500);
            }
            return AjaxResult.success(userlist);
        } catch (Exception e) {
            tRwbMapper.updateIsTranBySid("0", rwb.getSid());
            return AjaxResult.error(e.getMessage());

        }
    }

    private static List<TUserFk> buildUserFk(List<JSONObject> mergedSet, String workid) {
//        Long deptId = getLoginDept();
        List<TUserFk> users = mergedSet.stream().map(m -> new TUserFk(
                UUID.randomUUID().toString().replaceAll("-", ""),
                m.getString("id"),
                m.getString("nickname"),
                StringUtils.isEmpty(m.getString("post")) ? "无" : m.getString("post"),
                StringUtils.isEmpty(m.getString("phone")) ? "无" : m.getString("phone"),
                workid,
                m.getString("username"),
                StringUtils.isEmpty(m.getString("belong_company")) ? "无" : m.getString("belong_company"),
                null,
                DateUtils.getTime(),
                ZdjcEnum.WD.getValue()
                )
        ).collect(Collectors.toList());
        return users;
    }

    private static Long getLoginDept() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptId = user.getDeptId();
        return deptId;
    }

    @Override
    @Transactional
    public AjaxResult updateIsTranBySid(String sid,Boolean isUpdate,String ly) {
        try {
            if (StringUtils.isBlank(ly)) {
                return AjaxResult.success("ly为空");
            }
            if (StringUtils.isBlank(sid)) {
                return AjaxResult.success("sid为空");
            }
            if ("1".equals(ly)) {
                TRwb tRwb = tRwbMapper.selectById(sid);
                if ("1".equals(tRwb.getIsTran())) {
                    return AjaxResult.success("请勿重复转发");
                }
                if (isUpdate){
                    tRwbMapper.updateIsTranBySid("1", sid);
                }
                return AjaxResult.success(tRwbMapper.selectById(sid));
            }else{
                TZjxdRwb tZjxdRwb = tZjxdRwbMapper.selectById(sid);
                if ("1".equals(tZjxdRwb.getIsTran())) {
                    return AjaxResult.success("请勿重复转发");
                }
                if (isUpdate){
                    tZjxdRwbMapper.updateIsTranBySid("1", sid);
                }
                return AjaxResult.success(tZjxdRwbMapper.selectById(sid));
            }

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public AjaxResult getLoginUserInfoByAppToken(String appToken,String appCode) {
        if (StringUtils.isEmpty(appToken)) return AjaxResult.error("token为空");
        try {
            String appAuthCode = AESUtil.Encrypt(appCode, LzmxEnum.SECRETKEY.getValue());
            Map<String,String> params = new HashMap<>();
            params.put("appAuthCode", appAuthCode);
            params.put("appToken", appToken);
            String s = HttpUtils.sendPost(LZ_BASE_URL + "/smartservice/sso/getUserInfoByAppToken", JSONObject.toJSONString(params),new HashMap<>());
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject.getInteger("code") == 200) {
                JSONObject data = jsonObject.getJSONObject("data");
                Long userId = data.getLong("userId");
                String username = data.getString("username");
                List<LzUserPost> result = lzUserPostMapper.getIdByUserIdAndPostWay(userId, 2);
                int size = result.size();
                data.put("isleader", size == 0 ? "0" : "1");
                data.put("username", username);
                return AjaxResult.success(data);
            } else {
                return AjaxResult.error(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

//    @Override
//    public AjaxResult getDepartmentList(Map<String, String> params) {
//        try {
//            Map<String,String> param = new HashMap<>();
//            param.put("departmentId", "");
//            param.put("departmentName", "");
//            param.put("departmentCode", "");
//            Map<String,String> heards = new HashMap<>();
//            String appId = LzmxEnum.YJXD_APPID.getValue();
//            heards.put("appId", appId);
//            heards.put("AuthCode", getAuthCode(LzmxEnum.SECRETKEY.getValue(),appId));
//            heards.put("companyCode", getCompanyCode(LzmxEnum.SECRETKEY.getValue(),LzmxEnum.QYBM.getValue()));
//            String s = HttpUtils.sendPost(LZ_BASE_URL + "/smartservice-openapi/openApi/innerapp/department/list", JSONObject.toJSONString(param),heards);
//            JSONObject result = JSONObject.parseObject(s);
//            if (result.getInteger("code") == 200) {
//                List<JSONObject> depts= (List<JSONObject>) result.get("data");
//                List<TreeNode<String>> nodeList = depts.stream().map(m -> new TreeNode<String>(m.getString("departmentId"), m.getString("parentId"), m.getString("name"), m.getInteger("sort"))).collect(Collectors.toList());
//                List<Tree<String>> trees = TreeUtils.build(nodeList, LzmxEnum.TOP_DEPTID.getValue());
//                Collections.reverse(trees);
//                return AjaxResult.success(trees);
//            } else {
//                return AjaxResult.error(result.getString("message"));
//            }
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//    }

    @Override
    public AjaxResult getDepartmentList1(Map<String, String> params) {
        try {
            SysUser loginUser = getLoginUser();
            params.put("accountId", loginUser.getAccountId());
            params.put("isSyjt", isSyjt(loginUser));// 1省应急厅 0不是省应急厅下部门下的人(省应急厅组织架构下)
            List<LzDepartment>  depts = lzDepartmentMapper.getDepartmentScope(params);
            return AjaxResult.success(depts);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    private String isSyjt(SysUser loginUser) {
        // 判断当前人员是否为省应急厅部门下的人
        Map<String, String> params = new HashMap<>();
        params.put("accountId", loginUser.getAccountId());
        params.put("companyId", "1770716421732159489");
        List<LzDepartment>  syjtDept = lzDepartmentMapper.getAllParentDept(params);
        return syjtDept.size() > 0 ? "1" : "0";
    }

    @Override
    public AjaxResult getDepartmentList(Map<String, String> params) {
        try {
            List<LzDepartment> depts = new ArrayList<>();
            String topValue = LzmxEnum.TOP_DEPTID.getValue();
            if (StringUtils.isNotEmpty(params.get("deptId"))) {
                String deptId = params.get("deptId");
                LzDepartment lzDepartment = lzDepartmentMapper.selectById(deptId);
                topValue =String.valueOf(lzDepartment.getParentId());
                depts = lzDepartmentMapper.getAllSonDept(params);
            }else {
                depts = lzDepartmentMapper.getAllByDeletedOrderBySortDesc(params);
            }

            List<TreeNode<String>> nodeList = depts.stream().map(dept -> new TreeNode<String>(String.valueOf(dept.getId()), String.valueOf(dept.getParentId()), dept.getName(), -dept.getSort())).collect(Collectors.toList());
            List<Tree<String>> trees = TreeUtils.build(nodeList, topValue);
            if (trees != null) {
                Collections.reverse(trees);
            }
            return AjaxResult.success(trees);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
//    @Override
//    @Transactional
//    public AjaxResult andUserByDeptAndLaber(SelectUserVo selectUserVo) {
//        List<String> deptIds = selectUserVo.getDeptIds();
//        List<String> tabIds = selectUserVo.getTabIds();
//        String workid =  selectUserVo.getWorkid();
//        Result result = addSendUser(deptIds, tabIds,workid);
//        if (result.getCode() == 200) {
//            return AjaxResult.success(workid);
//        } else {
//            return AjaxResult.error(result.getMsg());
//        }
//
//    }
    @Override
    @Transactional
    public AjaxResult andUserByDeptAndLaber(SelectUserVo selectUserVo) {
        List<String> deptIds = selectUserVo.getDeptIds();
        List<String> tabIds = selectUserVo.getTabIds();
        String workid =  selectUserVo.getWorkid();
        Result result = addSendUser(deptIds, tabIds,workid);
        if (result.getCode() == 200) {
            return AjaxResult.success(workid);
        } else {
            return AjaxResult.error(result.getMsg());
        }

    }

//    @Override
//    public AjaxResult getUserLabelList(Map<String, String> params) {
//        try {
//            Map<String,String> heards  = new HashMap<>();
//            String appId = LzmxEnum.YJXD_APPID.getValue();
//            heards.put("appId", appId);
//            heards.put("AuthCode", getAuthCode(LzmxEnum.SECRETKEY.getValue(),appId));
//            heards.put("companyCode", getCompanyCode(LzmxEnum.SECRETKEY.getValue(),LzmxEnum.QYBM.getValue()));
//            String s = HttpUtils.sendGet(LZ_BASE_URL+"/smartservice-openapi/openApi/innerapp/user-label/list","", Constants.UTF8,heards);
//            JSONObject jsonObject = JSONObject.parseObject(s);
//            if (jsonObject.getInteger("code") == 200) {
//                return AjaxResult.success(jsonObject.getJSONArray("data"));
//            } else {
//                return AjaxResult.error(jsonObject.getString("message"));
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

    @Override
    public AjaxResult getUserLabelList(Map<String, String> params) {
        try {
            List<LzUserLabel> labels = lzUserLabelMapper.getIdAndName();
           return AjaxResult.success(labels);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public AjaxResult updateCysjByfkId(Map<String, String> params) {
        try {
            TUserFk tUserFk = tUserFkMapper.selectById(params.get("sid"));
            if (StringUtils.isBlank(tUserFk.getCysj())) {
                tUserFk.setCysj(params.get("cysj"));
            } else {
                Integer cysj = Integer.valueOf(tUserFk.getCysj()) + Integer.valueOf(params.get("cysj"));
                tUserFk.setCysj(String.valueOf(cysj));
            }
            tUserFkMapper.updateById(tUserFk);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public AjaxResult importData(List<TUserExcel> userList,String workid) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("userList", userList);
            params.put("workid", workid);
            List<JSONObject> userMap=  lzUserMapper.getUserInfoInPhone(params);
            List<TUserFk> users = buildUserFk(userMap, workid);
            if (users.size() > 0) {
                if (users.size() > 0) {
                    String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
        //            List<TUserFk> oldUsers = getRedisUser(key);
        //            users.addAll(oldUsers);
        //            // 删除原来成员
        //            redisTemplate.delete(key);
        //            // 去重
        //            users = deduplicateById(users);
                    addREdisByLimit(users,key);
                }
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @Override
    public TZjxdRwb getZjxdRwbInfo(String sid) {
        TZjxdRwb tZjxdRwb = tZjxdRwbMapper.selectById(sid);
        List<TZjxdRwb> rwbs = new ArrayList<>();
        rwbs.add(tZjxdRwb);
        addFkslZjxd(rwbs); // 添加反馈状态
        List<TFjb> tFjbs = getFjbs(sid);
        tZjxdRwb.setFjbs(tFjbs);
        List<File> files = new ArrayList<>();
        for (TFjb tFjb : tFjbs) {
            files.add(new File(tFjb.getWjwldz()));
        }
        tZjxdRwb.setFjFile(files);

        // 判断是在办 还是 查看
        SysUser user = getLoginUser();
        Long deptId = user.getDeptId();
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        if ("区县".equals(sysDept.getDeptLevel())){// 区县（执行下发企业操作）
            tZjxdRwb.setIsQx(true);
        } else if ("市级".equals(sysDept.getDeptLevel())){
            List<TOption> options = tOptionMapper.getDeptIdAndDeptNameByRwbIdAndCreateDept(sid,deptId);
//            List<SysDept> collect = options.stream().map(m -> new SysDept(m.getDeptName(),m.getDeptId())).collect(Collectors.toList());
            List<Long> deptIds = options.stream().map(m -> m.getShowDeptId()).collect(Collectors.toList());
            tZjxdRwb.setDeptIds(deptIds);
        }
//        List<Map> parentOptions = tOptionMapper.getParentOptions(sid, deptId);
        List<Map> options = tOptionMapper.getOptions(sid, deptId);
//        tZjxdRwb.setParentOptions(parentOptions);// 父部门审批意见
//        tZjxdRwb.setOptions(options);// 本部门审批意见
        List<Long> roleIds = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<TOption> tOptions = tOptionMapper.getAllByDeptIdAndRwbId(deptId, sid,roleIds);
        if (tOptions.size() > 0) {
            tZjxdRwb.setSfsp("1".equals(tOptions.get(0).getSpStatus()));
            tZjxdRwb.setSpyj(tOptions.get(0).getSpyj());
        }
        tZjxdRwb.setInDo(tOptions.size()>0);
        return tZjxdRwb;
    }

    @Override
    public TZjxdRwb getAppZjxdRwbInfo(String sid, String username) {
        TZjxdRwb tZjxdRwb = tZjxdRwbMapper.selectById(sid);
        List<TZjxdRwb> rwbs = new ArrayList<>();
        rwbs.add(tZjxdRwb);
        addFkslZjxd(rwbs); // 添加反馈状态
        List<TFjb> tFjbs = getFjbs(sid);
        tZjxdRwb.setFjbs(tFjbs);
        List<File> files = new ArrayList<>();
        for (TFjb tFjb : tFjbs) {
            files.add(new File(tFjb.getWjwldz()));
        }
        tZjxdRwb.setFjFile(files);

        // 判断是在办 还是 查看
        SysUser user = sysUserMapper.selectUserbyAccountId(username);
        Long deptId = user.getDeptId();
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        TOption option = getOption(user.getUserId(), sid);
        if (ZdjcEnum.WD.getValue().equals(option.getFkzt())) {
            option.setFkzt(ZdjcEnum.YD.getValue());
            tOptionMapper.updateById(option);
        }
        List<String> loginRole = getLoginRoleNames(user);
        if ("区县".equals(sysDept.getDeptLevel())&&!loginRole.contains(ZdjcEnum.SJY.getValue())){// 区县（执行下发企业操作）
            tZjxdRwb.setIsQx(true);
        } else{
            if (loginRole.contains(ZdjcEnum.SJY.getValue())) {// 收件员 显示人员
                List<Long> roleIds2 = new ArrayList<>();
                roleIds2.addAll(Arrays.asList(104L,105L,106L));
                List<SysUser> userIds = tZjxdRwbMapper.getUserByDeptAndRoleId(deptId, roleIds2);
                tZjxdRwb.setTranUsers(userIds);
                List<Long> tran = tUserOptionMapper.getUserIdByRwbIdAndUserId(option.getId());
                tZjxdRwb.setCheckTranUsers(tran);
                tZjxdRwb.setIsSjy(true);
            }else{
                List<TOption> options = tOptionMapper.getDeptIdAndDeptNameByRwbIdAndCreateDept(sid,deptId);
                List<Long> deptIds = options.stream().map(m -> m.getShowDeptId()).collect(Collectors.toList());
                tZjxdRwb.setDeptIds(deptIds);
            }
        }
        List<Long> rolest = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<Map> parentOptions = tOptionMapper.getParentOptions(option.getId());
//        List<Map> options = tOptionMapper.getOptions(sid, deptId);
        tZjxdRwb.setParentOptions(parentOptions);// 父部门审批意见
        tZjxdRwb.setOption(option);// 本部门审批意见
        if (option!=null){
            tZjxdRwb.setSfsp("1".equals(option.getSpStatus()));
            tZjxdRwb.setSpyj(option.getSpyj());
        }
        tZjxdRwb.setInDo(option.getId()!=null);
        addZjxdFksl(tZjxdRwb);
        return tZjxdRwb;
    }

    @Override
    @Transactional
    public void updateZjxdRwb(XdrwVo xdrwVo) {
        TZjxdRwb rwb = xdrwVo.getZjxdRwb();
        String sid = rwb.getSid();
        tZjxdRwbMapper.updateById(rwb);// 修改下达任务
        // 修改附件表信息 先删除再添加
        UpdateWrapper<TFjb> fjbUpdateWrapper = new UpdateWrapper<>();
        fjbUpdateWrapper.eq("rwb_id", sid);
        tFjbMapper.delete(fjbUpdateWrapper);
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            } else {
                TFjb fjb = new TFjb();
                fjb.setWjdz(json.getString("url"));
                fjb.setWjwldz(json.getString("filePath"));
                String fileName = json.getString("name");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                tFjbMapper.insert(fjb);
            }
        }
    }

    @Override
    public AjaxResult tranXdrw(XdrwVo xdrwVo) {
        SysUser user = getLoginUser();
        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        Long deptId = getLoginDept();
        List<Long> roleIds = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        TOption option = getOption(deptId, zjxdRwb,roleIds);
        updateOption(option, xdrwVo.getSpyj());
        String sid = zjxdRwb.getSid();
        // 添加反馈信息
        List<String> deptIds = xdrwVo.getDeptIds();
        List<SysDept> sysDepts = sysDeptMapper.selectAllByDeptIdIn(deptIds);

        List<TOption> options = sysDepts.stream().map(d -> new TOption(sid, d.getDeptId(), d.getDeptName(), "0", d.getDeptLevel(),deptId,option.getId())).collect(Collectors.toList());
        tOptionService.saveBatch(options);
        System.out.println(options);
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                fjb.setFkbId(option.getId());
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success();
    }
    @Override
    public AjaxResult tranAppXdrw(XdrwVo xdrwVo) {

        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        SysUser user = sysUserMapper.selectUserbyAccountId(xdrwVo.getUsername());
        Long deptId = user.getDeptId();
//        List<Long> roleIds = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        TOption option = getOption(user.getUserId(), zjxdRwb.getSid());
        updateAppOption(option, xdrwVo.getSpyj(), user);
        String sid = zjxdRwb.getSid();
        // 添加反馈信息
        List<String> loginRole = getLoginRoleNames(user);
        List<TOption> options = new ArrayList<>();
        if (loginRole.contains(ZdjcEnum.SJY.getValue())) {// 如果当前人角色是收件员转给科室主任、分管领导、一把领导
//            options =sysDepts.stream().map(d -> new TOption(sid, deptId, d.getDeptName(), "0", d.getDeptLevel(),deptId,option.getId(),getTranRoleId(d.getDeptName()),d.getDeptId())).collect(Collectors.toList());
            SysDept d = sysDeptMapper.selectDeptById(deptId);
            TOption tOption = new TOption(sid, deptId, d.getDeptName(), "0", d.getDeptLevel()+ZdjcEnum.LD.getValue(), null, option.getId(), null, d.getDeptId());
            options.add(tOption);
            tOptionService.saveBatch(options);
            List<SysUser> userIds = xdrwVo.getUserIds();
            for (SysUser sysUser : userIds) {
                TUserOption tUserOption = new TUserOption(sysUser.getUserId(), tOption.getId(), sid);
                tUserOptionMapper.insert(tUserOption);
            }
        } else {// 如果当前人角色不是收件员转给收件员
            List<String> deptIds = xdrwVo.getDeptIds();
            List<SysDept> sysDepts = sysDeptMapper.selectAllByDeptIdIn(deptIds);
            options = sysDepts.stream().map(d -> new TOption(sid, d.getDeptId(), d.getDeptName(), "0", d.getDeptLevel()+ZdjcEnum.SJY.getValue(),deptId,option.getId(),getTranRoleId(ZdjcEnum.SJY.getValue()),d.getDeptId())).collect(Collectors.toList());
            tOptionService.saveBatch(options);
            List<Long> roleIds2 = new ArrayList<>();
            roleIds2.add(ZdjcEnum.SJY_ID.getLongValue());
            addUserOption(options,sid,roleIds2);
        }
        System.out.println(options);
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                fjb.setFkbId(option.getId());
                tFjbMapper.insert(fjb);
            }
        }
        return AjaxResult.success();
    }

    private TOption getOption(Long deptId, TZjxdRwb zjxdRwb,List<Long> roleIds) {
        List<TOption> options1 = tOptionMapper.getAllByDeptIdAndRwbId(deptId, zjxdRwb.getSid(),roleIds);
        TOption optionId = new TOption();
        if (options1.size()>0){
            optionId= options1.get(0);
        }
        return optionId;
    }

    private TOption getOption(Long userId,String rwbId) {
        List<TOption> options1 = tOptionMapper.getOption(userId,rwbId);
        TOption optionId = new TOption();
        if (options1.size()>0){
            optionId= options1.get(0);
        }
        return optionId;
    }

    public AjaxResult tranXdrwToUser(XdrwVo xdrwVo) {
        // 修改意见表
        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        Long deptId = getLoginDept();
        SysUser user = getLoginUser();
        List<Long> roleIds = getLoginRoles(user).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        TOption option = getOption(deptId, zjxdRwb,roleIds);
        updateOption(option,xdrwVo.getSpyj());
        if ("2".equals(xdrwVo.getLy())) {// 移动端
            String workid = UUID.randomUUID().toString().replace("-", "");
            zjxdRwb.setWorkid(workid);
            xdrwVo.setWorkid(workid);
            Result sendUser = addSendUser(xdrwVo.getDeptIds(), xdrwVo.getTabIds(), workid);
        }else {
            zjxdRwb.setWorkid(xdrwVo.getWorkid());
        }
//        zjxdRwb.setWorkid(workid);
        tZjxdRwbMapper.updateById(zjxdRwb);// 关联任务id
        List<TUser> users = tUserMapper.getUserByWorkId(xdrwVo);
        // 添加反馈信息
        long start = System.nanoTime();
        String sid = xdrwVo.getZjxdRwb().getSid();
        List<TFkb> fkbs = users.stream().map(u -> new TFkb(sid, u.getId(), DateUtils.getTime(), ZdjcEnum.WD.getValue())).collect(Collectors.toList());
//        tFkbService.saveBatch(fkbs);
        if (fkbs.size()>0){
            tFkbMapper.insertBatch(fkbs);
        }

        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(sid);
                fjb.setFkbId(option.getId());
                tFjbMapper.insert(fjb);
            }
        }

        TRwb rwb = new TRwb();
        rwb.setSxbt(zjxdRwb.getSxbt());
        rwb.setSffk(zjxdRwb.getSffk());
        rwb.setJzrq(zjxdRwb.getJzrq());

        // 发送消息到企业微信
//        messageSendByLimit(users,rwb,500);
        return AjaxResult.success();
    }
    public AjaxResult tranAppXdrwToUser(XdrwVo xdrwVo) {
        // 修改意见表
        TZjxdRwb zjxdRwb = xdrwVo.getZjxdRwb();
        SysUser user = sysUserMapper.selectUserbyAccountId(xdrwVo.getUsername());
        TOption option = getOption(user.getUserId(), zjxdRwb.getSid());
        updateAppOption(option, xdrwVo.getSpyj(), user);
        List<TUserFk> users = new ArrayList<>();
        if ("2".equals(xdrwVo.getLy())) {// 移动端
            String workid = UUID.randomUUID().toString().replace("-", "");
            zjxdRwb.setWorkid(workid);
            xdrwVo.setWorkid(workid);
            Result sendUser = addAppSendUser(xdrwVo.getDeptIds(), xdrwVo.getTabIds(), workid,zjxdRwb.getSid());
            users = sendUser.getData();
        }else {
            zjxdRwb.setWorkid(xdrwVo.getWorkid());
        }
        tZjxdRwbMapper.updateById(zjxdRwb);// 关联任务id
        // 添加附件表信息
        List<JSONObject> fjbs = xdrwVo.getFjbs();
        for (JSONObject json : fjbs) {
            JSONObject fjInfo = json.getJSONObject("response");
            if (StringUtils.isNotNull(fjInfo)) {
                TFjb fjb = new TFjb();
                fjb.setWjdz(fjInfo.getString("url"));
                fjb.setWjwldz(fjInfo.getString("filePath"));
                String fileName = fjInfo.getString("originalFilename");
                fjb.setWjmc(fileName);
                fjb.setWjlx(FileTypeUtils.getFileType(fileName));
                fjb.setCjsj(DateUtils.getTime());
                fjb.setRwbId(zjxdRwb.getSid());
                fjb.setFkbId(option.getId());
                tFjbMapper.insert(fjb);
            }
        }

        TRwb rwb = new TRwb();
        rwb.setSxbt(zjxdRwb.getSxbt());
        rwb.setSffk(zjxdRwb.getSffk());
        rwb.setJzrq(zjxdRwb.getJzrq());
        rwb.setSid(zjxdRwb.getSid());

        // 发送消息到企业微信
        messageSendByLimit(users,rwb,500);
        return AjaxResult.success();
    }

    private void updateOption(TOption tOption, String spyj) {
        SysUser user = getLoginUser();
        tOption.setSpsj(new Date());
        tOption.setSprId(user.getUserId());
        tOption.setSprName(user.getNickName());
        tOption.setSpStatus("1");
        tOption.setSpyj(spyj);
        tOptionMapper.updateById(tOption);
    }
    private void updateAppOption(TOption tOption, String spyj,SysUser user) {
        tOption.setSpsj(new Date());
        tOption.setSprId(user.getUserId());
        tOption.setSprName(user.getNickName());
        tOption.setSpStatus("1");
        tOption.setSpyj(spyj);
        tOptionMapper.updateById(tOption);
    }
    private SysUser getLoginUser(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser.getUser();
    }

    public void messageSend(List<TUserFk> users,TRwb rwb) {
        try {
            String ly = "1";
            String companyCode = "jlyj";
            String publicAcct = "yjfk";
            String secretKey = "asdfghjkl1234567";
            Map<String, Object> params = new HashMap<>();
            params.put("token", MD5(companyCode+publicAcct+secretKey+new SimpleDateFormat("yyyyMMdd").format(new Date())));
            params.put("publicAcct", publicAcct);
            params.put("companyCode", companyCode);
            params.put("toAcctType", "1");
            params.put("pushType", "100");
            params.put("toAcctInfo", users.stream().map(TUserFk::getUserName).collect(Collectors.toSet()));
            params.put("title", "一键直达系统消息");
            params.put("message", "您有一项新的任务事项,事项名称:《"+rwb.getSxbt()+"》"+("1".equals(rwb.getSffk())&&StringUtils.isNotBlank(rwb.getJzrq())?",需要您在"+rwb.getJzrq()+"前进行反馈":""));
            params.put("pushContent", "文案");
            params.put("appCode", "yjfk");
            params.put("pushTime", DateUtils.getTime());
            Map<String, Object> startParam = new HashMap<>();
            startParam.put("startType","3");
            startParam.put("h5Url","http://36.97.236.76:8083?rwbId="+rwb.getSid()+"&ly="+ly+"&isTz=1");
            startParam.put("pcUrl","http://36.97.236.76:8083?rwbId="+rwb.getSid()+"&ly="+ly+"&isTz=1");
            params.put("startParam", startParam);
            Map<String,String> heards = new HashMap<>();
            String appId = LzmxEnum.YJXD_APPID.getValue();
            heards.put("appId", appId);
            heards.put("AuthCode", getAuthCode(LzmxEnum.SECRETKEY.getValue(),appId));
            String s = HttpUtils.sendPost(LZ_BASE_URL + "/smartservice/im/pushContent", JSONObject.toJSONString(params),heards);
            log.info("发送通知结果为" + s);
            tUserFkMapper.updateTsztBySidIn(users.stream().map(TUserFk::getSid).collect(Collectors.toList()));
            // 发送消息到辰安
            messageSendCA(users, rwb);
            // 发送消息到森详
            messageSendSX(users, rwb);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void messageSendCA(List<TUserFk> users,TRwb rwb) {
        try {
            rwb = tRwbMapper.selectById(rwb.getSid());
            Map<String, Object> params = new HashMap<>();
//            params.put("messageContent", "您有一项新的任务事项,事项名称:《"+rwb.getSxbt()+"》"+("1".equals(rwb.getSffk())&&StringUtils.isNotBlank(rwb.getJzrq())?",需要您在"+rwb.getJzrq()+"前进行反馈":""));
            params.put("messageContent", rwb.getXdnr());
            params.put("sendName",getLoginUser().getNickName());
            params.put("loginNames", users.stream().map(TUserFk::getUserName).collect(Collectors.toSet()));
//            params.put("loginNames", new String[]{"13843016832"});
            params.put("sendOrgName","一键直达");
            params.put("filePath", getFjbs(rwb.getSid()).stream().map(TFjb::getWjdz).collect(Collectors.joining(";")));
            params.put("taskId", rwb.getSid());
            Map<String, Object> eventInfo = new HashMap<>();// 事项信息
            eventInfo.put("releaseTime", rwb.getXdrq());// 下达时间
            eventInfo.put("nature", selectDictLabel("sxxz",rwb.getSxxz()));// 事项性质
            eventInfo.put("type", selectDictLabel("sxlx",rwb.getSxlx()));//事项类型
            eventInfo.put("urgency", selectDictLabel("jjcd",rwb.getJjcd()));//紧急程度
            eventInfo.put("deadline", rwb.getJzrq());//截止日期
            eventInfo.put("phone",rwb.getLxdh() );//联系电话
            params.put("eventInfo", eventInfo);
            String encryptedAES = EncryptionUtil.encryptWithAES(JSONObject.toJSONString(params), "JRWAPSbXoAgWLnUI");
            Map map = new HashMap();
            map.put("data", encryptedAES);
            log.info("辰安消息推送数据" + JSONObject.toJSONString(map));
            String s = HttpUtils.sendPost("https://aqjdjczhgl.ajj.changchun.gov.cn/gsdss-api/si/api/message/v1/receive", JSONObject.toJSONString(map), new HashMap<>());
            log.info("辰安消息推送结果"+s);
        } catch (Exception e) {

        }
    }

    private void messageSendSX(List<TUserFk> users, TRwb rwb) {
        try {
            // 获取token
            String tokenResult = HttpUtils.sendGet("http://36.135.85.170:7633/getDirectToken?key=zV2379XuVeYgFBk8");
            log.info("获取森详token" + tokenResult);
            JSONObject jsonObject = JSONObject.parseObject(tokenResult);
            // 调用推送消息接口
            Map<String, String> heards = new HashMap<>();
            heards.put("Authorization", jsonObject.getString("data"));
            if (jsonObject.getInteger("code") == 200) {
                Map<String, Object> json = new HashMap();
//            ArrayList<String> toAcctInfo = new ArrayList<>();
//            toAcctInfo.add("17411111111");
//            toAcctInfo.add("18504325263");
//            toAcctInfo.add("13538687141");
//            toAcctInfo.add("13300001112");
//            toAcctInfo.add("18400000011");
//            toAcctInfo.add("18400001111");
//            toAcctInfo.add("15500003333");
//            toAcctInfo.add("17412341234");
//            toAcctInfo.add("15500002222");
//            toAcctInfo.add("13300001111");
//            toAcctInfo.add("13300001113");
//            toAcctInfo.add("13944220000");
//            toAcctInfo.add("13944228888");
//            json.put("toAcctInfo", toAcctInfo);
                json.put("toAcctInfo", users.stream().map(TUserFk::getUserName).collect(Collectors.toSet()));
                json.put("message", "您有一项新的任务事项,事项名称:《" + rwb.getSxbt() + "》" + ("1".equals(rwb.getSffk()) && StringUtils.isNotBlank(rwb.getJzrq()) ? ",需要您在" + rwb.getJzrq() + "前进行反馈" : ""));
                json.put("pushTime", DateUtils.getTime());
                String pushResult = HttpUtils.sendPost("http://36.135.85.170:7633/externalData/pushMessage", JSONObject.toJSONString(json), heards);
                log.info("森详消息推送结果" + pushResult);
            } else {
                log.error("调用森详获取token接口异常" + tokenResult);
            }
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        // 获取token
        String tokenResult = HttpUtils.sendGet("http://36.135.85.170:7633/getDirectToken?key=zV2379XuVeYgFBk8");
        log.info("获取森详token"+tokenResult);
        JSONObject jsonObject = JSONObject.parseObject(tokenResult);
        if (jsonObject.getInteger("code") == 200) {
            // 调用推送消息接口
            Map<String,String> heards = new HashMap<>();
            heards.put("Authorization", jsonObject.getString("data"));
            Map<String,Object> json = new HashMap();
            ArrayList<String> toAcctInfo = new ArrayList<>();
            toAcctInfo.add("17412341234");
            json.put("toAcctInfo", toAcctInfo);
            json.put("message", "测试内容");
//        json.put("message", "您有一项新的任务事项,事项名称:《"+rwb.getSxbt()+"》"+("1".equals(rwb.getSffk())&&StringUtils.isNotBlank(rwb.getJzrq())?",需要您在"+rwb.getJzrq()+"前进行反馈":""));
            json.put("pushTime", DateUtils.getTime());
            String url2 = HttpUtils.sendPost("http://36.135.85.170:7633/externalData/pushMessage",JSONObject.toJSONString(json),heards);
            log.info("森详消息推送结果"+url2);
        } else {
            log.error("调用森详获取token接口异常" + tokenResult);
        }
    }




    /**
     * 获取辰安读取状态
     * @param users
     * @param rwId 任务表id
     */
    public void setCaReadstatus(List<TUserFk> users,String rwId) throws Exception {
        for (TUserFk user : users) {
            Map<String, Object> params = new HashMap<>();
            params.put("loginName", user.getPhone());
            params.put("taskId", rwId);
//            params.put("loginName", "13843016832");
            String encryptedAES = EncryptionUtil.encryptWithAES(JSONObject.toJSONString(params), "JRWAPSbXoAgWLnUI");
            Map map = new HashMap();
            map.put("data", encryptedAES);
//            String s = HttpUtils.sendPost("https://30m3717k91.goho.co/api/message/v1/readstatus", JSONObject.toJSONString(map), new HashMap<>());
            String s = HttpUtils.sendPost("https://aqjdjczhgl.ajj.changchun.gov.cn/gsdss-api/si/api/message/v1/readstatus", JSONObject.toJSONString(map), new HashMap<>());
            log.info("辰安获取人员" + JSONObject.toJSONString(map) + "读取状态结果" + s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if ("1".equals(jsonObject.getString("data"))) {// 如果辰安人员读取状态为已读
                if ("1".equals(user.getZt())) {// 如果人员反馈表 状态为未读  变为已读
                    user.setZt("2");
                    tUserFkMapper.updateById(user);
                }
            }
        }
    }

    private String selectDictLabel(String dictType, String dictValue){
        String s = sysDictDataMapper.selectDictLabel(dictType, dictValue);
        return StringUtils.isNotEmpty(s) ? s : "";
    }

    private Result addSendUser(List<String> deptIds, List<String> tabIds,String workid){
        // 查询部门下成员
        try {
            List<JSONObject> userList = new ArrayList<>();
            if (deptIds.size()>0 && tabIds.size()>0) {// 既选部门又选标签 查询人员条件为 部门+标签
                Map<String, Object> params = new HashMap<>();
                params.put("deptIds", deptIds);
                params.put("tabIds", tabIds);
                params.put("postWay", 2);
                userList = lzUserMapper.getUserBydeptAndLabel(params);
            } else {
                if (deptIds.size() > 0) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("deptIds", deptIds);
                    params.put("tabIds", tabIds);
                    params.put("postWay", 2);
                    userList = lzUserMapper.getUserBydeptAndLabel(params);
                }
                if (tabIds.size() > 0) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("tabIds", tabIds);
                    params.put("postWay", 2);
                    userList = lzUserMapper.getUserByLabel(params);
                }
            }
            List<TUserFk> users = buildUserFk(userList, workid);
            // 去重
            // 查出上次选择的人员 放入集合中整体去重
            String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
//            List<TUserFk> oldUsers = getRedisUser(key);
//            users.addAll(oldUsers);
//            // 删除原来成员
//            redisTemplate.delete(key);
//            // 去重
//            users = deduplicateById(users);
            if (users.size() > 0) {
                addREdisByLimit(users,key);
            }
            return new Result().success(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Result addAppSendUser(List<String> deptIds, List<String> tabIds,String workid,String rwbId){
        // 查询部门下成员
        try {
            List<JSONObject> userList = new ArrayList<>();
            if (deptIds.size()>0 && tabIds.size()>0) {// 既选部门又选标签 查询人员条件为 部门+标签
                Map<String, Object> params = new HashMap<>();
                params.put("deptIds", deptIds);
                params.put("tabIds", tabIds);
                params.put("postWay", 2);
                userList = lzUserMapper.getUserBydeptAndLabel(params);
            } else {
                if (deptIds.size() > 0) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("deptIds", deptIds);
                    params.put("tabIds", tabIds);
                    params.put("postWay", 2);
                    userList = lzUserMapper.getUserBydeptAndLabel(params);
                }
                if (tabIds.size() > 0) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("tabIds", tabIds);
                    params.put("postWay", 2);
                    userList = lzUserMapper.getUserByLabel(params);
                }
            }
            List<TUserFk> users = buildUserFk(userList, workid);
            // 去重
            users = deduplicateById(users);
            if (users.size() > 0) {
                // 保存
                long l = System.nanoTime();
                users.stream().forEach(u->u.setRwbId(rwbId));
                saveUserByLimit(users);
//                tUserFkMapper.insertBatch(users);
                long l1 = System.nanoTime();
                System.out.println("添加人员用时" + (l1 - l) / 1000000000 + "ms");
            }
            return new Result().success(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    private String getAuthCode(String secretKey,String appId) throws Exception {
        String sSrc = appId+"@"+DateUtils.getTime();
        String Encrypt = AESUtil.Encrypt(sSrc,secretKey);
        return Encrypt;
    }
    private String getCompanyCode(String secretKey,String qybm) throws Exception {
        String Encrypt = AESUtil.Encrypt(qybm,secretKey);
        return Encrypt;
    }
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f', 'g' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    private void addFksl(List<TRwb> rwbs) {
        for (TRwb rwb : rwbs) {
            //查询反馈状态
            Map<String, String> fkzt = tRwbMapper.getFkzt(rwb.getSid());
            rwb.setXdsl(fkzt.get("xdsl"));
            rwb.setYxdsl(fkzt.get("yxdsl"));
            rwb.setYdsl(fkzt.get("ydsl"));
            rwb.setWdsl(fkzt.get("wdsl"));
            rwb.setYfk(fkzt.get("yfk"));
            rwb.setWfk(fkzt.get("wfk"));
        }
    }
    private void addZjxdFksl(TZjxdRwb zjxdRwb) {
            //查询反馈状态
            Map<String, String> fkzt = tRwbMapper.addZjxdFksl(zjxdRwb.getSid());
            zjxdRwb.setXdsl(fkzt.get("xdsl"));
            zjxdRwb.setYdsl(fkzt.get("ydsl"));
            zjxdRwb.setWdsl(fkzt.get("wdsl"));
            zjxdRwb.setYfk(fkzt.get("yfk"));
            zjxdRwb.setWfk(fkzt.get("wfk"));
    }

    private void addZjxdUserFksl(TZjxdRwb zjxdRwb) {
            //查询反馈状态
            Map<String, String> fkzt = tRwbMapper.getFkzt(zjxdRwb.getSid());
            zjxdRwb.setXdsl(fkzt.get("xdsl"));
            zjxdRwb.setYdsl(fkzt.get("ydsl"));
            zjxdRwb.setWdsl(fkzt.get("wdsl"));
            zjxdRwb.setYfk(fkzt.get("yfk"));
            zjxdRwb.setWfk(fkzt.get("wfk"));
    }

    private void addFkslZjxd(List<TZjxdRwb> zjxdRwbs) {
        for (TZjxdRwb rwb : zjxdRwbs) {
            //查询反馈状态
            Map<String, String> fkzt = tRwbMapper.getFkzt(rwb.getSid());
            rwb.setXdsl(fkzt.get("xdsl"));
            rwb.setYdsl(fkzt.get("ydsl"));
            rwb.setWdsl(fkzt.get("wdsl"));
            rwb.setYfk(fkzt.get("yfk"));
            rwb.setWfk(fkzt.get("wfk"));
        }
    }
    private Integer getPage(Map<String,String> params){
        return Integer.valueOf(params.get("page"));
    }
    private Integer getPage1(Map<String,Object> params){
        return Integer.valueOf(String.valueOf(params.get("page")));
    }
    private Integer getLimit(Map<String,String> params){
        return Integer.valueOf(params.get("limit"));
    }
    private Integer getLimit1(Map<String,Object> params){
        return Integer.valueOf(String.valueOf(params.get("limit")));
    }

    private Long getJgByBm(SysDept sysDept){
        if (sysDept==null) return null;
        if ("1".equals(sysDept.getDeptType())) {// 1机构 2部门
            return sysDept.getDeptId();
        } else {
            SysDept sysDept1 = sysDeptMapper.selectDeptById(sysDept.getParentId());
            if (sysDept1==null){
                return sysDept.getDeptId();
            }
            return getJgByBm(sysDept1);
        }
    }


    private void messageSendByLimit(List<TUserFk> list ,TRwb tRwb,int limitNum) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        int size = list.size();
        //批次数
        int batchNum = size % limitNum == 0 ? size / limitNum : size / limitNum + 1;
        boolean falg = size % limitNum != 0;
        for (int i = 0; i < batchNum; i++) {
            if (falg && i == batchNum - 1) {
                //size/limitNum取余数(除不尽),计算end的索引值
                limitNum = size % limitNum;
            }
            List<TUserFk> batchList = list.subList(0, limitNum);
            messageSend(batchList,tRwb);
            System.out.println("第" + i + batchList);
            list.subList(0, limitNum).clear();
        }
    }
    private void ssmSendByLimit(List<TUserFk> list ,TRwb tRwb)  throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        int numberOfThreads = ZdjcEnum.THREAD_COUNT.getIntValue();
        int chunkSize = list.size() / numberOfThreads;

        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            int start = i * chunkSize;
            int end = (i == numberOfThreads - 1) ? list.size() : (i + 1) * chunkSize;
            List<TUserFk> chunk = list.subList(start, end);
            executorService.submit(() -> {
                for (TUserFk tUserFk : chunk) {
                    if (StringUtils.isNotEmpty(tUserFk.getPhone())){
                        ssmSend(tUserFk.getPhone(), tRwb);
                    }
                }
            });
        }
        executorService.shutdown(); // 关闭ExecutorService
//        executorService.awaitTermination(10, TimeUnit.SECONDS); // 等待所有任务完成
    }
    private void saveUserByLimit(List<TUserFk> list) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        int numberOfThreads = ZdjcEnum.THREAD_COUNT.getIntValue();
        int chunkSize = list.size() / numberOfThreads;

        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            int start = i * chunkSize;
            int end = (i == numberOfThreads - 1) ? list.size() : (i + 1) * chunkSize;
            List<TUserFk> chunk = list.subList(start, end);

            executorService.submit(() -> {
                tUserFkMapper.insertBatch(chunk);
            });
        }
        executorService.shutdown(); // 关闭ExecutorService
        executorService.awaitTermination(10, TimeUnit.SECONDS); // 等待所有任务完成
    }
    private void addREdisByLimit(List<TUserFk> list,String key) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        int numberOfThreads = ZdjcEnum.THREAD_COUNT.getIntValue();
        int chunkSize = list.size() / numberOfThreads;
        ListOperations<Object, Object> listOps = redisTemplate.opsForList();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            int start = i * chunkSize;
            int end = (i == numberOfThreads - 1) ? list.size() : (i + 1) * chunkSize;
            List<TUserFk> chunk = list.subList(start, end);
            executorService.submit(() -> {
                listOps.rightPushAll(key,chunk.toArray());
            });
        }
        executorService.shutdown(); // 关闭ExecutorService
        executorService.awaitTermination(10, TimeUnit.SECONDS); // 等待所有任务完成
    }

    @Override
    public AjaxResult queryUserByUsername(String username) {
        SysUser user = sysUserMapper.selectUserbyAccountId(username);
        if (user == null) {
            return AjaxResult.error("未有该功能权限！");
        }else{
            return AjaxResult.success(user);
        }
    }

    @Override
    public AjaxResult getSonDeptOptionInfo(Map<String, String> params) {
        String rwbId = params.get("rwbId");
        Long deptId = getLoginDept();
        List<TOption> tOptions = tOptionMapper.getAllByRwbIdAndCreateDept(rwbId, deptId);
        return AjaxResult.success(tOptions);
    }
    @Override
    public AjaxResult getSonDeptOptionInfoById(Map<String, String> params) {
        String optionId = params.get("optionId");
        List<TOption> tOptions = tOptionMapper.getAllByParentId(optionId);
        return AjaxResult.success(tOptions);
    }

    @Override
    public AjaxResult getDeptByUserId(XdrwVo xdrwVo) {
        try {
            if (xdrwVo.getUserId() == null) throw new RuntimeException("userId不能为空");
            List<Map> tranUserDept = lzUserPostMapper.getTranUserDept(xdrwVo.getUserId());
            return AjaxResult.success(tranUserDept);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageInfo<Map> getChildOptions(Map<String, String> params) {
        PageHelper.startPage(getPage(params), getLimit(params));
        List<Map> childOptions = tOptionMapper.getChildOptions(params);
        return new PageInfo<>(childOptions);
    }

    @Override
    public List<Map<String, Integer>> getSxlxCountData(Map<String, String> params) {
        return tRwbMapper.getSxlxCountData(params);
    }

    @Override
    public void delSelectUser(XdrwVo xdrwVo) {
        String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + xdrwVo.getWorkid();
        ListOperations<Object, Object> operations = redisTemplate.opsForList();
        for (TUserFk user : xdrwVo.getUserFks()) {
            operations.remove(key,0,user);
        }
    }

    @Override
    public AjaxResult delRedisUserByKey(Map<String, String> params) {
        String workid = params.get("workid");
        String key = ZdjcEnum.SAVE_SEND_USER_KEK.getValue() + workid;
        Boolean delete = redisTemplate.delete(key);
        return AjaxResult.success(delete);

    }

    @Override
    public AjaxResult messageSendByLimit(XdrwVo xdrwVo) {
        try {
            TRwb rwb = xdrwVo.getRwb();
            List<TUserFk> users = tUserFkMapper.getAllByWorkid(xdrwVo.getWorkid());
            messageSendByLimit(users,rwb,500);
            return AjaxResult.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AjaxResult ssmSendByLimit(XdrwVo xdrwVo) {
        try {
            TRwb rwb = xdrwVo.getRwb();
            List<TUserFk> users = tUserFkMapper.getAllByWorkid(xdrwVo.getWorkid());
            ssmSendByLimit(users,rwb);
            return AjaxResult.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void ssmSend(String mobile,TRwb rwb) {
        Map<String,Object> params = new HashMap<>();
        String sKey = "996d750889ae4dce";
        params.put("mobile",AESUtil.encryptCbc(mobile,sKey) );
        params.put("signature", AESUtil.encryptCbc("DXQM_000000084",sKey));
        params.put("template", AESUtil.encryptCbc("DXMB_000000087",sKey));
        params.put("smsid", AESUtil.encryptCbc(IdUtils.simpleUUID(),sKey));
        params.put("timestamp", AESUtil.encryptCbc(String.valueOf(new Date().getTime()),sKey));
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("content", " 您有一项新的任务事项,事项名称:《" + rwb.getSxbt() + "》" + ("1".equals(rwb.getSffk()) && StringUtils.isNotBlank(rwb.getJzrq()) ? ",需要您在" + rwb.getJzrq() + "前进行反馈" : "")+",请前往一键直达系统进行查看");
        params.put("paramsEncry", AESUtil.encryptCbc(JSONObject.toJSONString(paramsMap),sKey));
        Map<String,String> heards = new HashMap<>();
        heards.put("key", "86c6aa88f1ad4a8a84998c5f0aba8579");
        String s = HttpUtils.sendPost("https://sms.ahdict.cn:9888/sms/send", JSONObject.toJSONString(params),heards);
        System.out.println("发送短信结果为"+s);
    }

    @Override
    public AjaxResult getXdrwByWorkid(Map<String, String> params) {
        List<TRwb> tRwbs = tRwbMapper.getSidByWorkid(params.get("workid"));
        if (tRwbs.size()==0) throw new RuntimeException("没有查到任务表数据");
        return AjaxResult.success(tRwbs.get(0));
    }

    @Override
    public AjaxResult getFkIdByRwbAndUserId(Map<String, String> params) {
        return AjaxResult.success(tRwbMapper.getFkIdByRwbAndUserId(params));
    }

    @Override
    public AjaxResult getUserDepartment(Map<String, String> params) {
        params.put("accountId", getLoginUser().getAccountId());
        List<LzDepartment> list = lzDepartmentMapper.getUserDepartment(params);
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getMyToDo(Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        params.put("type", "wd");
        result.put("wdsl", tRwbMapper.getFkxxByUserId(params).size());
        params.put("type", "wfk");
        result.put("wfksl", tRwbMapper.getFkxxByUserId(params).size());
        params.put("type", "yfk");
        result.put("yfksl", tRwbMapper.getFkxxByUserId(params).size());
        params.put("type", "yd");
        result.put("ydsl", tRwbMapper.getFkxxByUserId(params).size());
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult getMyToDoDone(Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        params.put("type", "db");// 待办
        result.put("dbsl", tRwbMapper.getFkxxByUserId(params).size());
        params.put("type", "yb");// 已办
        result.put("ybsl", tRwbMapper.getFkxxByUserId(params).size());
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult getInstitutionCount(Map<String, String> params) {
        List<Map<String, Object>> result = new ArrayList<>();
        Integer xcsCount = 0;
        switch (params.get("type")) {
            case "fxkh":
                params.put("labelType", "5");// 查询防汛抗旱标签下的人员
                result = lzUserMapper.getUserCountByLabel(params);
                params.put("parentId", "1796876308365946881");// 查询防汛抗旱下的人员
                List<LzUserLabel> fxkhLabel = lzUserLabelMapper.getFxkhLabel(params);
//                notDataShowZero1(fxkhLabel, result);// 没有数据的数量显示为0
//                for (LzUserLabel lzUserLabel : fxkhLabel) {
//                    Map<String, Object> jydw = new HashMap<>();
//                    jydw.put("deptName", lzUserLabel.getName());
//                    Map<String, Object> params1 = new HashMap<>();
//                    params1.put("labelId", lzUserLabel.getId());
//                    jydw.put("count", lzUserMapper.getFxkhLabelUser(params1));
//                    result.add(jydw);
//                }
                break;
            case "aqsc":
                params.put("parentId", "1799721238872436737");// 查询生产经营单位下的公司
                result = lzDepartmentMapper.getDeptCountByParentId(params);
                List<LzDepartment> deptList = lzDepartmentMapper.getDeptByParentId(params);
//                notDataShowZero2(deptList, result);// 没有数据的数量显示为0
//                for (LzDepartment lzDepartment : deptList) {
//                    Map<String, Object> aqsc = new HashMap<>();
//                    aqsc.put("deptName", lzDepartment.getName());
//                    Map<String, Object> params1 = new HashMap<>();
//                    params1.put("deptId", lzDepartment.getId());
//                    aqsc.put("count", lzDepartmentMapper.getCompanyCountByDeptId(params1));
//                    result.add(aqsc);
//                }
//                Map<String, Object> xxcs = new HashMap<>();
//                xxcs.put("deptName", "小场所");
//                xxcs.put("count", lzDepartmentMapper.getSmallPlacesCompanyCount());
//                result.add(xxcs);
                xcsCount = lzDepartmentMapper.getSmallPlacesCompanyCount(params);
                break;
            case "slfh":
                params.put("parentId", "1808033509126098946");// 查询森林防火各个部门下的人员
                result = lzUserPostMapper.getUserCountByDept(params);
                List<LzDepartment> clfhDeptList = lzDepartmentMapper.getDeptByParentId(params);
//                notDataShowZero2(clfhDeptList, result);// 没有数据的数量显示为0
//                for (LzDepartment lzDepartment : clfhDeptList) {
//                    Map<String, Object> jydw = new HashMap<>();
//                    jydw.put("deptName", lzDepartment.getName());
//                    Map<String, Object> params1 = new HashMap<>();
//                    params1.put("deptId", lzDepartment.getId());
//                    jydw.put("count", lzDepartmentMapper.getUserCountByDeptId(params1));
//                    result.add(jydw);
//                }
                break;
            case "jydw":
                params.put("parentId", "1807962352662269954");// 查询应急队伍下的部门
                result = lzUserPostMapper.getUserCountByDept(params);
                List<LzDepartment> jydwDeptList = lzDepartmentMapper.getDeptByParentId(params);
//                notDataShowZero2(jydwDeptList, result);// 没有数据的数量显示为0
//                for (LzDepartment lzDepartment : jydwDeptList) {
//                    Map<String, Object> jydw = new HashMap<>();
//                    jydw.put("deptName", lzDepartment.getName());
//                    Map<String, Object> params1 = new HashMap<>();
//                    params1.put("deptId", lzDepartment.getId());
//                    jydw.put("count", lzDepartmentMapper.getUserCountByDeptId(params1));
//                    result.add(jydw);
//                }
                break;
        }
//        try {
//            Collections.sort(result, new Comparator<Map<String, Object>>() {
//                @Override
//                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//                    Float bl1 = Float.valueOf(o1.get("count").toString());
//                    Float bl2 = Float.valueOf(o2.get("count").toString());
//                    return bl2.compareTo(bl1);
//                }
//            });
//        } catch (Exception e) {
//
//        }

        return AjaxResult.success(result).put("xcscount",xcsCount);
    }

    private void notDataShowZero1(List<LzUserLabel> fxkhLabel, List<Map<String, Object>> result) {
        for (LzUserLabel lzUserLabel : fxkhLabel) {
            boolean notContainsKey = false;
            for (Map<String, Object> map : result) {
                if (StringUtils.isNotEmpty(lzUserLabel.getName())&& lzUserLabel.getName().equals(map.get("deptName"))) {
                    notContainsKey = true;
                }
            }
            if (!notContainsKey){
                Map<String, Object> map = new HashMap<>();
                map.put("deptName", lzUserLabel.getName());
                map.put("count", 0);
                result.add(map);
            }
        }
    }
    private void notDataShowZero2(List<LzDepartment> fxkhLabel, List<Map<String, Object>> result) {
        for (LzDepartment lzDepartment : fxkhLabel) {
            boolean notContainsKey = false;
            for (Map<String, Object> map : result) {
                if (StringUtils.isNotEmpty(lzDepartment.getName())&& lzDepartment.getName().equals(map.get("deptName"))) {
                    notContainsKey = true;
                }
            }
            if (!notContainsKey){
                Map<String, Object> map = new HashMap<>();
                map.put("deptName", lzDepartment.getName());
                map.put("count", 0);
                result.add(map);
            }
        }
    }


    @Override
    public PageInfo<TRwb> getYfbxx(Map<String, String> params) {
        List<TRwb> rwbs = new ArrayList<>();
        if (params.containsKey("myMatter")) {
            params.put("xdrId", String.valueOf(getLoginUser().getUserId()));
        }
        PageHelper.startPage(getPage(params), getLimit(params));
        rwbs = tRwbMapper.getRwPage(params);
        if ("WEB".equalsIgnoreCase(params.get("ly"))) {
            addFksl(rwbs);// 添加反馈状态
        }
        // 格式化下达日期
        for (TRwb rwb : rwbs) {
            String xdrq = rwb.getXdrq();
            if (xdrq != null) {
                if (xdrq.contains(" ")) {
                    rwb.setXdrq(xdrq.split(" ")[0]);
                }
            }
        }
        PageInfo<TRwb> pageInfo = new PageInfo<>(rwbs);
        return pageInfo;
    }

    @Override
    public AjaxResult getStatisticsSelectData(Map<String, Object> params) {
       List<LzDepartment> deptList = lzDepartmentMapper.getStatisticsSelectData(params);
        return AjaxResult.success(deptList);
    }
}




